﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Data.Linq;
using System.Drawing;
using Website.Logger;
using DAL;
using BOL;
using System.Web.Script.Services;
using System.Web.Services;
using UtilityExtensions;


namespace UILGestion.ObraAdmin.RendicionCaja
{
    public partial class RendicionCajaGrid : System.Web.UI.UserControl
    {

        public  RendicionCajaGrid()

        {
            item = new RendicionBL();
        }
        private RendicionBL item;

        public GridView itemGrid{ 
            get
        {
            return this.itemGrid;
        }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public void Load(string idPadre, string idRendic, int idestado,decimal IGV)
        {
            idParent.Value = idPadre;
            idRendicion.Value = idRendic;
            IGVLBL.Value = IGV.ToString();
            idEstado.Value = idestado.ToString();
            BindDataItem();
        }

        public void updateTotalesview()
        {




            //if (this.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.ID == "PartidaItem2gridCrtl1")
            //{

            //}
            var a=((UILGestion.ObraAdmin.RendicionCaja.RendicioneditForm)this.Page);
            a.setestadistica();

            if (this.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.ID == "RendicionGrupoGrid1")
            {
               RendicionGrupoGrid partidaItemGridCrtl1 =
               (RendicionGrupoGrid)this.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent;

                int index = ((GridViewRow)this.Parent.Parent.Parent.Parent.Parent).RowIndex;
                partidaItemGridCrtl1.BindDataItem();
                partidaItemGridCrtl1.MonstrarDetalle(index, idParent.Value);
            }
            
        }

        protected void DeleteItem(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                item.DeleteRendicionItem(idInternal);
                
                    updateTotalesview();
                    BindDataItem();
                
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void AddItem(object sender, EventArgs e)
        {
            try
            {
                Button lnkdivrecurso = (Button)sender;

                TextBox fechaTxt =
                    ((TextBox)itemGridView.FooterRow.FindControl("fechaTxt"));
                DropDownList tipodocumentoDDL =
                    ((DropDownList)itemGridView.FooterRow.FindControl("tipodocumentoDDL"));
                TextBox nroDocumentoTxt =
                    ((TextBox)itemGridView.FooterRow.FindControl("nroDocumentoTxt"));
                TextBox descripcionTxt =
                    ((TextBox)itemGridView.FooterRow.FindControl("descripcionTxt"));

                
                TextBox conceptoTxt =
                    ((TextBox)itemGridView.FooterRow.FindControl("conceptoTxt"));
                TextBox totalTxt =
                    ((TextBox)itemGridView.FooterRow.FindControl("totalTxt"));
                TextBox idProveedorTXT =
                    ((TextBox)itemGridView.FooterRow.FindControl("idProveedorTXT"));

                TextBox tipoTXT =
                    ((TextBox)itemGridView.FooterRow.FindControl("tipoTXT"));
              

                    ////verificar el tipo de cambio del dia
                   // System.IFormatProvider MiFp =
                   //new System.Globalization.CultureInfo("es-ES", false);

                   // DateTime fechaComparativo = DateTime.ParseExact(fechaInsertTextBox.Text, "dd/MM/yyyy", MiFp);
                
                   if (tipodocumentoDDL.SelectedValue!="17" & tipoTXT.Text=="EMPLEADO")
                   {
                       throw new Exception("Debe registrar un PROVEEDOR");
                   }

                
                

                item.AddRendicionItem(fechaTxt.Text.ToDate().Value,
                                    tipodocumentoDDL.SelectedValue.ToInt(),
                                    nroDocumentoTxt.Text,
                                    descripcionTxt.Text,
                                    conceptoTxt.Text,
                                    totalTxt.Text.ToDecimal().Value,
                                    IGVLBL.Value.ToDecimal().Value,
                                    idParent.Value.ToInt(),
                                    idRendicion.Value.ToInt(),
                                    idProveedorTXT.Text.ToInt2(),
                                    tipoTXT.Text);



                updateTotalesview();
                BindDataItem();
                // GridUpdatePanel.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void UpdateItem2(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                

                GridView gv = ((GridView)sender);

                TextBox fechaTxt =
                   ((TextBox)gv.Rows[e.RowIndex].FindControl("fechaTxt"));
                DropDownList tipodocumentoDDL =
                    ((DropDownList)gv.Rows[e.RowIndex].FindControl("tipodocumentoDDL"));
                TextBox nroDocumentoTxt =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("nroDocumentoTxt"));
                TextBox descripcionTxt =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("descripcionTxt"));
                
                TextBox conceptoTxt =
                    ((TextBox)itemGridView.FooterRow.FindControl("conceptoTxt"));
                TextBox totalTxt =
                    ((TextBox)itemGridView.FooterRow.FindControl("totalTxt"));


                int idinternal = int.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());
                var rendicionItem = DbUtil.Db.RendicionItems.Single(p => p.idInternal == idinternal);
                int idEmpleadoEmisor = int.Parse(System.Web.HttpContext.Current.Session["idEmpleado"].ToString());
               
                rendicionItem.SetUpdate(fechaTxt.Text.ToDate().Value,
                                        tipodocumentoDDL.SelectedValue.ToInt(),
                                        nroDocumentoTxt.Text,
                                        descripcionTxt.Text,
                                        conceptoTxt.Text,
                                        totalTxt.Text.ToDecimal().Value,
                                        idEmpleadoEmisor);
                                        


                DbUtil.Db.SubmitChanges();
                gv.EditIndex = -1;
                itemGridView.FooterRow.Visible = true;
                updateTotalesview();
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditItem2(object sender, GridViewEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                gv.EditIndex = e.NewEditIndex;
                BindDataItem();
                gv.FooterRow.Visible = false;
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        public void BindDataItem()
        {
           


            itemGridView.DataSource = item.getRecepcionItemList(idParent.Value.ToInt()).ToList();
            
           

            if (idEstado.Value.ToInt() != 39)  //abierto
            {
                itemGridView.ShowFooter = false;
                itemGridView.Columns[6].Visible = false;
                itemGridView.DataBind();
            }
            else
            {
                itemGridView.Columns[6].Visible = true;
                itemGridView.DataBind();
                resetEmpty(itemGridView);
                setFooter();
            }
            

        }
        private void setFooter()
        {
            DropDownList tipodocumentoDDL =
                ((DropDownList)itemGridView.FooterRow.FindControl("tipodocumentoDDL"));

            
            tipodocumentoDDL.DataTextField = "descripcion";
            tipodocumentoDDL.DataValueField = "idInternal";
            tipodocumentoDDL.DataSource = new ListValueBL().GetDocumentoTipoCajaChica();
            tipodocumentoDDL.DataBind();
        }
        protected void CancelItem2(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);

                gv.EditIndex = -1;
                gv.FooterRow.Visible = true;
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        private void resetEmpty(GridView gv)
        {
            if (gv.Rows.Count == 0)
            {
                List<RendicionItemInfo> itemList0 = new List<RendicionItemInfo>();
                RendicionItemInfo itemcero = new RendicionItemInfo();

                itemList0.Add(itemcero);
                gv.DataSource = itemList0;
                gv.DataBind();
                gv.Rows[0].Visible = false;
            }

        }
    }
}